package com.btl.cygf;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;
import com.btl.bean.ZuiXin;
import com.btl.sqlite.DbOpService;
import com.btl.sqlite.History;
import com.btl.ui.adapter.MyListView;
import com.btl.utils.DownTuUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ZhuanJiActivity extends Activity implements OnClickListener{
	ImageView login_backtofragment;   //返回 
	private TextView zhuanjitouming;  
	private TextView zhuanjitoujianjie;  
	private ImageView zhuanjitoupic;  
	private LinkedList<ZuiXin> listItems = new LinkedList<ZuiXin>(); // 数据源集合
	private MyListView mListView;
	private AsyncHttpClient client;  
	private RequestParams params; 
	
	private String z_name;
	private String z_jianjie;
	private String  picurl;
	private String z_id;
	private LinearLayout chakanzhuanji;
	
	private MyListAdapter myListAdapter; // 适配器 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.zhuanjione);
		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		zhuanjitouming=(TextView) findViewById(R.id.zhuanjitouming);
		zhuanjitoujianjie=(TextView) findViewById(R.id.zhuanjitoujianjie);
		zhuanjitoupic=(ImageView) findViewById(R.id.zhuanjitoupic);
		
		mListView = (MyListView) findViewById(R.id.list_zhuanji);
		chakanzhuanji=(LinearLayout) findViewById(R.id.chakanzhuanji);
		
		login_backtofragment.setOnClickListener(this);
		chakanzhuanji.setOnClickListener(this);
		Intent intent=getIntent();
		z_name = intent.getStringExtra("zhuanjitouming");
		z_jianjie = intent.getStringExtra("zhuanjitoujianjie");
		z_id = intent.getStringExtra("z_id");
		picurl = intent.getStringExtra("zhuanjitoupic");
		
		zhuanjitouming.setText(z_name);
		zhuanjitoujianjie.setText(z_jianjie);
		ImageLoader imageLoader = ImageLoader.getInstance();
		imageLoader.init(DownTuUtils.getConfig(this));
		imageLoader.displayImage(picurl, zhuanjitoupic, DownTuUtils.getOptions());
		
		client = new AsyncHttpClient();
		// 像网络传输的数据
		params = new RequestParams();
		// 链接到网络，获取数据
		getDataRefresh();
		
		myListAdapter = new MyListAdapter();
		mListView.setAdapter(myListAdapter);
	}
	
	
	private void getDataRefresh() {
		params.remove("z_id");
		params.add("z_id", z_id);
		client.post(getResources().getString(R.string.url)
				+ "/CYGF/ModelZhuanJI", params,
				new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						
						for (int i = 0; i < response.length(); i++) {
							ZuiXin zuiXin = new ZuiXin();
							JSONObject object = response.optJSONObject(i);
							String s1 = object.optString("v_image");
							String s2 = object.optString("v_title");
							String s4 = object.optString("v_intro");
							String s5 = object.optString("p_id");
							int s6 = object.optInt("v_dianzan");
							String s7 = object.optString("p_nickname");
							int s10 = object.optInt("v_id");
							zuiXin.setPicture(s1);
							zuiXin.setTitle(s2);
							zuiXin.setInfo(s4);
							if (s7 == null) {
								zuiXin.setUsername(s5);
							} else {
								zuiXin.setUsername(s7);
							}
							zuiXin.setDianzan(s6);
							zuiXin.setVid(s10);
							System.out.println(zuiXin.getPicture());
							listItems.add(zuiXin);
							zuiXin = null;
						}
						
						
						myListAdapter.notifyDataSetChanged();
						super.onSuccess(statusCode, headers, response);
					}

					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
					}
				});
			}
	
	/**
	 * listview的适配器MyListAdapter 
	 */
	private class MyListAdapter extends BaseAdapter {

		class ListItemView {
			public ImageView image;
			public TextView title;
			public TextView info;
			public TextView zuozhe;
			public TextView dianzanshu;
		}

		@Override
		public int getCount() {
			return listItems.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					SharedPreferences share= getApplicationContext().getSharedPreferences("login"  , Activity.MODE_WORLD_READABLE);
					String username = share.getString("id", "");
					if(!username.equals("")){
						SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Date now = new Date();
						History history = new History();
						history.setUsername(username);
						history.setVid(listItems.get(position).getVid()+"");
						history.setTitle(listItems.get(position).getTitle());
						history.setIntro(listItems.get(position).getInfo());
						history.setVtime(myFmt.format(now));
						DbOpService db= new DbOpService(getApplicationContext());
						db.Insert(history);
					}
					Intent intent = new Intent();
					intent.setClass(ZhuanJiActivity.this, TieZiActivity.class);
					intent.putExtra("v_id",listItems.get(position).getVid()+"");
					
					startActivity(intent);
				}
			});
			// final int selectID = position;
			// 自定义视图
			ListItemView listItemView = null;
			if (convertView == null) {
				listItemView = new ListItemView();
				// 获取list_item布局文件的视图
				convertView = LayoutInflater.from(getApplicationContext()).inflate(
						R.layout.zuixin_item, null);
				// 获取控件对象
				listItemView.image = (ImageView) convertView
						.findViewById(R.id.zuixin_view);
				listItemView.title = (TextView) convertView
						.findViewById(R.id.zuixin_name);
				listItemView.info = (TextView) convertView
						.findViewById(R.id.zuixin_info);
				listItemView.zuozhe = (TextView) convertView
						.findViewById(R.id.zuixin_zuozhe);
				listItemView.dianzanshu = (TextView) convertView
						.findViewById(R.id.dianzanshu);
				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}

			final String str = listItems.get(position)
					.getPicture();
			System.out.println(str);
			System.out.println(listItems.get(position)
					.getTitle());

			ImageLoader imageLoader = ImageLoader.getInstance();

			imageLoader.init(DownTuUtils.getConfig(ZhuanJiActivity.this));

			imageLoader.displayImage(str, listItemView.image,
					DownTuUtils.getOptions());

			// listItemView.image.setImageBitmap(new
			// BitmapFactory().decodeByteArray(data, offset, length))
			listItemView.title.setText(listItems.get(
					position).getTitle());
			listItemView.info.setText(listItems.get(
					position).getInfo());
			listItemView.zuozhe.setText(listItems.get(
					position).getUsername());
			listItemView.dianzanshu.setText(listItems.get(
					position).getDianzan()
					+ "");
			return convertView;
		}

	}

	


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_backtofragment:
			this.finish();
			break;
		case R.id.chakanzhuanji:
			Intent it=new Intent();
			it.setClass(ZhuanJiActivity.this, SuoYouZhuanJiActivity.class);
			startActivity(it);
		default:
			break;
		}
	
		
	}
       
}
